<template>
  <div class="contract grid">
    <!-- 左 -->
    <div class="dataBoard_left flex flex-c">
      <contractStatistics class="mb-10 flex-1" />
      <!-- contract 承包 outsource 外包 -->
      <contractPie class="flex-1" />
    </div>
    <!-- 右 -->
    <div class="dataBoard_right flex flex-c">
      <contractRightTop class="mb-10 flex-1" @handleAddBtn="handleAddClick" @handleDetails="handleDetails"
        @handleEdit="handleEdit" :tableListData="tableData1" :listTotal="total1" @getHandleList="getHandleList1" />
      <contractRightMain class="flex-1" @handleAddBtn="handleAddClick" @handleDetails="handleDetails"
        @handleEdit="handleEdit" :tableListData="tableData2" :listTotal="total2" @getHandleList="getHandleList2" />
    </div>
    <el-dialog title="添加合同" v-model="dialogVisible" width="50%" draggable align-center destroy-on-close
      :before-close="handleClose">
      <el-form :model="form" ref="loginFormRef" :rules="loginRules" label-width="100px">
        <el-form-item label="合作单位" prop="signingUnit">
          <el-select v-model="form.signingUnit" placeholder="请选择合作单位" size="large" style="width: 100%"
            @change="businessNameChange">
            <el-option v-for="item in unitOption" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="合同名称" prop="businessName">
          <el-input v-model="form.businessNameId" placeholder="请选择合同单位" size="large" style="width: 100%"></el-input>
        </el-form-item>
        <!-- <el-form-item label="业务结构">
          <el-radio-group v-model="form.businessType">
            <el-radio value="1" size="large">承包</el-radio>
            <el-radio value="2" size="large">外包</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="下级分包单位" prop="signingUnitsss">
          <el-select v-model="form.signingUnitsss" placeholder="请选择下级分包单位" size="large" style="width: 100%" clearable>
            <el-option v-for="item in subcontractingUnitOptions" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- 业务类型 0小区厨余收运 1小区其他收运 3餐厨垃圾收运 4站点管理 -->
        <el-form-item label="业务类型" prop="attributeType">
          <el-radio-group v-model="form.attributeType" @change="radioGroupChange">
            <el-radio value="0" size="large" label="0">小区厨余收运</el-radio>
            <el-radio value="1" size="large" label="1">小区其他收运</el-radio>
            <el-radio value="3" size="large" label="3">餐厨垃圾收运</el-radio>
            <el-radio value="4" size="large" label="4">站点管理</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="日收运量" prop="collectionVolume">
          <el-input v-model="form.collectionVolume" show-word-limit maxlength="20" placeholder="请输入日收运量"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="服务对象" prop="businessId">
          <el-select v-model="form.businessId" placeholder="请选择服务对象" size="large" style="width: 100%" clearable>
            <el-option v-for="item in businessOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="起始时间" prop="startTime">
          <el-date-picker v-model="form.startTime" format="YYYY-MM-DD" value-format="YYYY-MM-DD" type="date"
            placeholder="请选择起始时间" style="width: 100%" clearable />
        </el-form-item>
        <el-form-item label="到期时间" prop="expirationTime">
          <el-date-picker v-model="form.expirationTime" format="YYYY-MM-DD" value-format="YYYY-MM-DD" type="date"
            placeholder="请选择到期时间" style="width: 100%" clearable />
        </el-form-item>
        <el-form-item label="上传文件">
          <el-upload v-model:file-list="fileList" class="upload-demo" action="/jeecg-boot/fileManage/upload" multiple
            :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :limit="1"
            :on-exceed="handleExceed" :headers="uploadHeaders">
            <el-button type="primary">上传文件</el-button>
            <template #tip>
              <div class="el-upload__tip">仅支持png、jpeg 格式</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {
  ref,
  computed,
  watch,
  onMounted,
  onBeforeUnmount,
  reactive,
  shallowRef,
} from "vue";
import { useStore } from "vuex";
import * as echarts from "echarts";
import contractPie from "./components/contract-left/contractPie.vue";
import contractStatistics from "./components/contract-left/contractStatistics.vue";
import contractRightTop from "./components/contract-right/contractRightTop.vue";
import contractRightMain from "./components/contract-right/contractRightMain.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
import { getToken, getUserInfo } from "@/utils/auth";

import {
  unitBusinessListApi, communityListApi, listAssociableSitesApi, unitListApi, addApi, editApi
} from "@/api/contract";
// const store = useStore(); 
let dialogVisible = ref(false);
let form = ref<any>({});
let tableData1 = ref<any>([]);
let tableData2 = ref<any>([]);
let loginFormRef: any = ref(null);
const pageSize1 = ref(10);
const currentPage1 = ref(1);
const total1 = ref(0);
const pageSize2 = ref(10);
const currentPage2 = ref(1);
const total2 = ref(0);
// 业务名称
let unitOption = ref<any>([]);
// 小区列表 
let communityList = ref<any>([]);
// 小区列表 
let listAssociableSitesList = ref<any>([]);
//下级分包单位
const subcontractingUnitOptions = ref<any>([]);
// 服务对象
const businessOptions = ref<any>([]);
const fileList = ref<UploadUserFile[]>([]);
const uploadHeaders = ref({
  "X-Access-Token": getToken(),
});
let loginRules: any = reactive({
  signingUnit: [
    {
      required: true,
      trigger: "blur",
      message: "请选择合作单位",
    },
  ],
  businessName: [
    {
      required: true,
      trigger: "blur",
      message: "请选择合同名称",
    },
  ],
  attributeType: [
    {
      required: true,
      trigger: "blur",
      message: "请选择业务类型",
    },
  ],
  collectionVolume: [
    {
      required: true,
      trigger: "blur",
      message: "请输入日收运量",
    },
  ],
  businessId: [
    {
      required: true,
      trigger: "blur",
      message: "请选择服务对象",
    },
  ],
  startTime: [
    {
      required: true,
      trigger: "blur",
      message: "请选择起始时间",
    },
  ],
  expirationTime: [
    {
      required: true,
      trigger: "blur",
      message: "请选择到期时间",
    },
  ],
});
const userInfo = ref<any>({});
onMounted(() => { init() });

onBeforeUnmount(() => { });
async function init() {
  if (!userInfo.value?.unitId) {
    try {
      userInfo.value = JSON.parse(getUserInfo());
    } catch (err) { }
  }
  getUnitBusinessList1();
  getUnitBusinessList2();
  getUnitList();
  await getCommunityList();
  businessOptions.value = communityList.value
  getListAssociableSites();
}
//承包 企业业务中心-分页列表查询
async function getUnitBusinessList1() {
  tableData1.value = []
  let info = {
    businessType: 0,//业务结构 0承包 1外包
    mainId: userInfo.value?.unitId,
    pageNo: currentPage1.value,
    pageSize: pageSize1.value,
  };
  const res = await unitBusinessListApi(info);
  if (res.status != 200) return;
  console.log("承包-企业业务中心-分页列表查询", res, res?.data);
  let { result = {} } = res?.data;
  tableData1.value = result?.records || []
}

//外包 企业业务中心-分页列表查询
async function getUnitBusinessList2() {
  tableData2.value = []
  let info = {
    businessType: 1,//业务结构 0承包 1外包
    mainId: userInfo.value?.unitId,
    pageNo: currentPage2.value,
    pageSize: pageSize2.value,
  };
  const res = await unitBusinessListApi(info);
  if (res.status != 200) return;
  console.log("外包-企业业务中心-分页列表查询", res, res?.data);
  let { result = {} } = res?.data;
  tableData2.value = result?.records || []
}
const getHandleList1 = (currentPage = 1, pageSize = 10) => {
  currentPage1.value = currentPage
  pageSize1.value = pageSize
  getUnitBusinessList1();
}
const getHandleList2 = (currentPage = 1, pageSize = 10) => {
  currentPage2.value = currentPage
  pageSize2.value = pageSize
  getUnitBusinessList2();

}
// 企业业务中心-通过单位id查询可关联的合作单位列表
async function getUnitList() {
  unitOption.value = []
  let info = {
    unitId: userInfo.value?.unitId,
  };
  const res = await unitListApi(info);
  if (res.status != 200) return;
  console.log("合作单位列表", res, res?.data);
  let { result = [] } = res?.data;
  unitOption.value = result.map((item: any) => {
    return {
      label: item.unitName,
      value: item.id
      // value: item.unitName
    }
  })
}
const businessNameChange = (e: any) => {
  let findObj = unitOption.value.find((item: any) => {
    return item.value == e
  })
  if (findObj != undefined) {
    form.value.businessName = findObj?.label
  }
}
// 企业业务中心-通过单位id查询可关联的 小区列表 
async function getCommunityList() {
  communityList.value = []
  let info = {
    unitId: userInfo.value?.unitId,
  };
  const res = await communityListApi(info);
  if (res.status != 200) return;
  console.log("小区  列表查询", res, res?.data);
  let { result = [] } = res?.data;
  communityList.value = result.map((item: any) => {
    return {
      label: item.name,
      value: item.id
    }
  })

}

// 企业业务中心-通过单位id可关联的站点列表
async function getListAssociableSites() {
  listAssociableSitesList.value = []
  let info = {
    unitId: userInfo.value?.unitId,
  };
  const res = await listAssociableSitesApi(info);
  if (res.status != 200) return;
  console.log("站点列表", res, res?.data);
  let { result = [] } = res?.data;
  listAssociableSitesList.value = result.map((item: any) => {
    return {
      label: item.siteName,
      value: item.id
    }
  })
}
const radioGroupChange = (e: any) => {
  console.log('业务类型', e);
  // 业务类型 0小区厨余收运 1小区其他收运 3餐厨垃圾收运 4站点管理
  form.value.businessId = ''
  if (e == 4) {
    businessOptions.value = listAssociableSitesList.value
  } else {
    businessOptions.value = communityList.value
  }
}
// 新增
const handleAddClick = (businessType = 0, scope = {}) => {
  dialogVisible.value = true;
  form.value.attributeType = '0'
  form.value.businessType = businessType
};
// 详情
const handleDetails = (businessType = 0, scope = {}) => {
  dialogVisible.value = true;
  form.value = scope
  form.value.businessType = businessType
};
// 编辑
const handleEdit = (businessType = 0, scope = {}) => {
  dialogVisible.value = true;
  form.value = scope
  form.value.businessType = businessType
};
// 关闭
const handleClose = () => {
  dialogVisible.value = false;
};
const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
  // if (file?.response?.code != 200) {
  //   return ElMessage.warning(file?.response?.message || "操作失败");
  // }
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning("只能上传一张图片，如已经上传一张了，请先清除再添加上传");
};
const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(`是否删除${uploadFile.name} ?`).then(
    () => true,
    () => false
  );
};
const submitForm = () => {
  // ElMessageBox.confirm("确定要提交表单吗？", "提示", {
  //   confirmButtonText: "确定",
  //   cancelButtonText: "取消",
  //   type: "warning",
  // })
  //   .then(() => {
  //     // 处理提交逻辑
  //     console.log(form.data);
  //     ElMessageBox.alert("提交成功", "提示", { type: "success" });
  //   })
  //   .catch(() => {
  //     // 取消提交逻辑
  //   });
  loginFormRef.value.validate(async (valid: any) => {
    if (!valid) return
    console.log('参数', form.value);
    if (!userInfo.value?.unitId) {
      try {
        userInfo.value = JSON.parse(getUserInfo());
      } catch (err) { }
    }
    let attributeType = Number(form.value.attributeType)
    let info: any = {
      mainId: userInfo.value?.unitId,
      signingUnit: form.value.signingUnit,
      pdfFile: form.value.pdfFile || '',//
      attributeType: attributeType,
      businessId: form.value.businessId,
      businessName: form.value.businessName,
      businessType: form.value.businessType,
      collectionVolume: form.value.collectionVolume,
      expirationTime: form.value.expirationTime,
      startTime: form.value.startTime,
    }
    let res: any = null
    if (form.value?.id) {
      info.id = form.value.id
      res = await editApi(info)
    } else {
      res = await addApi(info)
      console.log(111, res);
    }
    if (res?.data?.code === 200) {
      ElMessage.success(res?.msg || res?.data?.message)
      loginFormRef.value && loginFormRef.value.resetFields();
      getUnitBusinessList1();
      getUnitBusinessList2();
      handleClose()
    } else ElMessage.warning(res?.msg || res?.data?.message);

  });
};
</script>

<style lang="scss" scoped>
.contract {
  width: 100%;
  padding: 10px;
  grid-template-columns: 380px 2fr;
  grid-gap: 10px;
  height: 820px;

  .dataBoard_left {
    width: 100%;
  }

  .dataBoard_right {
    width: 100%;
  }
}
</style>